﻿using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Photograp.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

namespace Photograp.Controllers
{
    public class UploadController : Controller
    {
        private PhotographContext db = new PhotographContext();

        //
        // POST: /Upload/Edit/5
        [HttpPost]
        public ActionResult UploadPhotos(int id, IEnumerable<HttpPostedFileBase> files)
        {
            var album = db.Albums.Include(p => p.Photos).FirstOrDefault(p => p.AlbumId == id);

            var photos = new List<Photo>();
            if (album == null ) return null;

            foreach (HttpPostedFileBase file in files)
            {
                var account = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnection"].ConnectionString);
                var client = account.CreateCloudBlobClient();
                var container = client.GetContainerReference("productimages");

                if (container.CreateIfNotExists())
                {
                    // configure container for public access
                    var permissions = container.GetPermissions();
                    permissions.PublicAccess = BlobContainerPublicAccessType.Container;
                    container.SetPermissions(permissions);
                }
                
                string uniqueBlobName = string.Format("productimages/image_{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(file.FileName));
                var blob = container.GetBlockBlobReference(uniqueBlobName);
                blob.Properties.ContentType = file.ContentType;
                blob.UploadFromStream(file.InputStream);

                var url = blob.Uri.ToString();

                if (!string.IsNullOrWhiteSpace(url))
                {
                    var addon = new Photo
                    {
                        Description = file.FileName,
                        UrlPhoto = url,
                        CreatedOn = DateTime.Now,
                    };

                    photos.Add(addon);
                    album.Photos.Add(addon);
                }
            }

            db.SaveChanges();

            return Json(photos);
        }
    }
}
